package com.dldata.devtools30.controller.sysform;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dldata.devtools30.common.DataListCols;
import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.controller.DevBase30Controller;
import com.dldata.devtools30.entity.*;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplArgsDao;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplOtherBtnDao;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplTheaderDao;
import com.dldata.devtools30.repository.sysform.DevtFormMetadataDao;
import com.dldata.devtools30.service.metadata.DevtModelMetadataFieldService;
import com.dldata.devtools30.service.metadata.DevtModelMetadataTableService;
import com.dldata.devtools30.service.sysform.DevtFormDesignEntityService;
import com.dldata.devtools30.service.sysform.DevtFormListTemplateService;
import com.dldata.devtools30.service.sysform.DevtFormTypeService;
import com.dldata.devtools30.utils.*;
import com.google.common.collect.Lists;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by zhw on 2020-07-07.
 */
@Controller
@RequestMapping(value = "/V_SysFromPreviewController")
@Slf4j
public class V_DevtFromPreviewController extends DevBase30Controller {

    @Autowired
    private DevtFormListtemplTheaderDao sysCrfFormListtemplTheaderDao;
    @Autowired
    private DevtFormListTemplateService sysCrfFormListTemplateService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    DevtFormListtemplArgsDao sysCrfFormListtemplArgsDao;
    @Autowired
    DevtFormListtemplOtherBtnDao sysCrfFormListtemplOtherBtnDao;
    @Autowired
    DevtFormTypeService formTypeService;
    
    @Autowired
    DevtModelMetadataTableService metadataTableService;
    @Autowired
    DevtModelMetadataFieldService metadataFieldService;
    @Autowired
    DevtFormMetadataDao sysCrfFormMetadataDao;
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    DevtFormDesignEntityService formDesignService;

    @RequestMapping(value = "/toDldsnformPreview")
    public String toDldsnformPreview(Model model,@RequestParam Map<String, Object> param,HttpServletRequest request,HttpServletResponse httpServletResponse) throws SQLException {
        if(StrUtil.isEmpty((CharSequence)param.get("tempid"))&&!StrUtil.isEmpty((CharSequence)request.getAttribute("tempid"))){
            param.put("tempid",(CharSequence)request.getAttribute("tempid"));
        }
        if(StrUtil.isEmpty((CharSequence)request.getAttribute("bitoken"))){
            request.setAttribute("bitoken","");
        }

        JSONObject JsonOpt = new JSONObject();
        JSONObject config = new JSONObject();
        //弹窗宽高
        List<DevtFormDesignEntity> formDesignEntityList = formDesignService.getFormDesignDataByTempid(param.get("tempid").toString());
        if (formDesignEntityList.size()>0) {
            JsonOpt = JSON.parseObject(formDesignEntityList.get(0).getJsonOpt());
            config = JSON.parseObject(JsonOpt.get("config").toString());
        }
        model.addAttribute("config",config);

        //表格数据
        DevtFormListtemplateEntity sysCrfFormListtemplateEntityTmp = sysCrfFormListTemplateService.getTemplateById(param.getOrDefault("tempid", "").toString());
        if(sysCrfFormListtemplateEntityTmp==null){
            try {
                httpServletResponse.setContentType("text/html");
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.getWriter().println("表单id不存在:"+param.getOrDefault("tempid", "").toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        List<DataListCols> tableMapListPatient = new ArrayList<>();
        try {
            List<DataListCols> dataListColses = sysCrfFormListTemplateService.getDataListColses(sysCrfFormListtemplateEntityTmp);
            tableMapListPatient.addAll(dataListColses);
        }catch (Exception exception){
            try {
                httpServletResponse.setContentType("text/text");
                httpServletResponse.setCharacterEncoding("UTF-8");
                exception.printStackTrace(new PrintWriter(httpServletResponse.getWriter()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        model.addAttribute("tablePatientEntity", StringUtil.escape(JSON.toJSONString(sysCrfFormListtemplateEntityTmp)));
        model.addAttribute("tableMapListPatient",tableMapListPatient.size()>0? StringUtil.escape(JSON.toJSONString(tableMapListPatient)):null);
        model.addAttribute("tempid",param.getOrDefault("tempid", "").toString());

        model.addAttribute("addBtnCfg", sysCrfFormListtemplateEntityTmp.getThconf() != null && sysCrfFormListtemplateEntityTmp.getThconf().length()>1?sysCrfFormListtemplateEntityTmp.getThconf().charAt(1):"0");
        model.addAttribute("searchBtnCfg",sysCrfFormListtemplateEntityTmp.getThconf()!=null&&sysCrfFormListtemplateEntityTmp.getThconf().length()>0?sysCrfFormListtemplateEntityTmp.getThconf().charAt(0):"0");
        model.addAttribute("delBtnCfg",sysCrfFormListtemplateEntityTmp.getThcolconf()!=null&&sysCrfFormListtemplateEntityTmp.getThcolconf().length()>1?sysCrfFormListtemplateEntityTmp.getThcolconf().charAt(1):"0");
        model.addAttribute("editBtnCfg",sysCrfFormListtemplateEntityTmp.getThcolconf()!=null&&sysCrfFormListtemplateEntityTmp.getThcolconf().length()>0?sysCrfFormListtemplateEntityTmp.getThcolconf().charAt(0):"0");
        model.addAttribute("importBtnCfg",StringUtil.isNullOrSpace(sysCrfFormListtemplateEntityTmp.getImportconf())?"0":sysCrfFormListtemplateEntityTmp.getImportconf());
        //子表数据
        List<DataListCols> tableMapListSon=null;
        List<DevtFormListtemplateEntity>  tempfieldlist = sysCrfFormListTemplateService.getFormListtemplateByFormId(param.getOrDefault("tempid", "").toString());
        if (tempfieldlist.size()>0){
            //只需要管一个子表
            tableMapListSon = sysCrfFormListTemplateService.getDataListColses(tempfieldlist.get(0));

            //子表查询控件
            List<Map<String,Object>> sonSelectMapList = new ArrayList<Map<String,Object>>();
//            List <SysFormListtemplArgsEntity> customTypeEntityList = sysCrfFormListtemplArgsDao.getAllCloneData();
            List <DevtFormListtemplArgsEntity> customTypeEntityList = Lists.newArrayList( sysCrfFormListtemplArgsDao.findAll());
            customTypeEntityList.stream().filter(sysCrfFormListtemplTheaderEntity -> {
                        return sysCrfFormListtemplTheaderEntity.getTempleid().equals(tempfieldlist.get(0).getId());
                    }
            ).sorted(
                    new Comparator<DevtFormListtemplArgsEntity>() {
                        @Override
                        public int compare(DevtFormListtemplArgsEntity o1, DevtFormListtemplArgsEntity o2) {
                            return o1.getXh()-o2.getXh();
                        }
                    }
            ).forEach(
                    (entity) -> {
                        Map<String, Object> tmpmap = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(entity));
                        tmpmap.put("lxLable", EnumUtils.SEARCHLX.getFormValue(entity.getLx()).getLabel());
                        sonSelectMapList.add(tmpmap);
                    }
            );

            //   0#否/1#是
            sonSelectMapList.stream().forEach(selectMap->{
                StringBuilder lxdata = new StringBuilder();
                if (!StringUtil.isEmptyOrLength0(selectMap.get("lxdata"))&&selectMap.get("lxdata").toString().trim().startsWith("(select)")){
                    try {
                        List<Map<String,Object>> rows = jdbcTemplate.queryForList(selectMap.get("lxdata").toString().replace("(select)",""));
                        rows.stream().forEach(row->{
                            Set keySet = row.keySet();
                            int i=0;
                            for (Object keyName : keySet) {
                                i++;
                                lxdata.append(row.get(keyName));
                                if (i%2==0){
                                    lxdata.append("/");
                                }else {
                                    lxdata.append("#");
                                }
                            }

                        });

                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    if (lxdata.toString().endsWith("/")){
                        selectMap.put("lxdata",lxdata.toString().substring(0, lxdata.length() -1));
                    }else {
                        selectMap.put("lxdata",lxdata.toString());
                    }
                }
            });
            model.addAttribute("SonTempid",tempfieldlist.get(0).getId());
            model.addAttribute("sonSelectMapList", sonSelectMapList.size()==0?null:StringUtil.escape(JSON.toJSONString(sonSelectMapList)));


            //子表 编辑栏 添加栏
            List<Map<String,Object>> sonEditFieldList = new ArrayList<Map<String,Object>>();
//            List <SysFormListtemplOtherBtnEntity> sonTemplOtherBtnEntityList = sysCrfFormListtemplOtherBtnDao.getAllCloneData();
            List <DevtFormListtemplOtherBtnEntity> sonTemplOtherBtnEntityList = Lists.newArrayList( sysCrfFormListtemplOtherBtnDao.findAll());
            sonTemplOtherBtnEntityList.stream().filter(
                    sonSysFormListtemplTheaderEntity -> {
                        return sonSysFormListtemplTheaderEntity.getTempleid().equals(tempfieldlist.get(0).getId());
                    }
            ).sorted(
                    new Comparator<DevtFormListtemplOtherBtnEntity>() {
                        @Override
                        public int compare(DevtFormListtemplOtherBtnEntity o1, DevtFormListtemplOtherBtnEntity o2) {
                            return o1.getXh()-o2.getXh();
                        }
                    }
            ).forEach(
                    (sysCrfFormTemplateEntity) -> {
                        Map<String, Object> tmpmap = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(sysCrfFormTemplateEntity));
                        tmpmap.put("positionshow","编辑栏");
                        if(sysCrfFormTemplateEntity.getPosition().equalsIgnoreCase("add")){
                            tmpmap.put("positionshow","添加栏");
                        }
                        tmpmap.put("actionshow","弹窗");
                        if(sysCrfFormTemplateEntity.getAction().equalsIgnoreCase("nowin")){
                            tmpmap.put("actionshow","不弹窗");
                        }
                        if(sysCrfFormTemplateEntity.getAction().equalsIgnoreCase("newpage")){
                            tmpmap.put("actionshow","新页面");
                        }
                        tmpmap.put("useflagshow","是");
                        if(sysCrfFormTemplateEntity.getUseflag()==0){
                            tmpmap.put("useflagshow","否");
                        }
                        sonEditFieldList.add(tmpmap);
                    }
            );

            model.addAttribute("sonEditFieldList", StringUtil.escape(JSON.toJSONString(sonEditFieldList)));
        }

        model.addAttribute("tableMapListSon",StringUtil.isEmptyOrLength0(tableMapListSon)?null:StringUtil.escape(JSON.toJSONString(tableMapListSon)));
        model.addAttribute("tableSonEntity",tempfieldlist.size()==0?null:StringUtil.escape(JSON.toJSONString(tempfieldlist.get(0))));
        if (tempfieldlist.size()>0) {
            model.addAttribute("addSonBtnCfg", tempfieldlist.get(0).getThconf() != null && tempfieldlist.get(0).getThconf().length() > 1 ? tempfieldlist.get(0).getThconf().charAt(1) : "0");
            model.addAttribute("searchSonBtnCfg", tempfieldlist.get(0).getThconf() != null && tempfieldlist.get(0).getThconf().length() > 0 ? tempfieldlist.get(0).getThconf().charAt(0) : "0");
            model.addAttribute("delSonBtnCfg", tempfieldlist.get(0).getThcolconf() != null && tempfieldlist.get(0).getThcolconf().length() > 1 ? tempfieldlist.get(0).getThcolconf().charAt(1) : "0");
            model.addAttribute("editSonBtnCfg", tempfieldlist.get(0).getThcolconf() != null && tempfieldlist.get(0).getThcolconf().length() > 0 ? tempfieldlist.get(0).getThcolconf().charAt(0) : "0");
            model.addAttribute("importSonBtnCfg", StringUtil.isNullOrSpace(tempfieldlist.get(0).getImportconf())?"0":tempfieldlist.get(0).getImportconf());

        }else {
            model.addAttribute("addSonBtnCfg","0");
            model.addAttribute("searchSonBtnCfg","0");
            model.addAttribute("delSonBtnCfg","0");
            model.addAttribute("editSonBtnCfg","0");
            model.addAttribute("importSonBtnCfg","0");
        }

        //查询控件
        List<Map<String,Object>> selectMapList = new ArrayList<Map<String,Object>>();
//        List <SysFormListtemplArgsEntity> customTypeEntityList = sysCrfFormListtemplArgsDao.getAllCloneData();
        List <DevtFormListtemplArgsEntity> customTypeEntityList = Lists.newArrayList( sysCrfFormListtemplArgsDao.findAll());
        customTypeEntityList.stream().filter(sysCrfFormListtemplTheaderEntity -> {
                    return sysCrfFormListtemplTheaderEntity.getTempleid().equals(param.getOrDefault("tempid", "").toString());
                }
        ).sorted(
                new Comparator<DevtFormListtemplArgsEntity>() {
                    @Override
                    public int compare(DevtFormListtemplArgsEntity o1, DevtFormListtemplArgsEntity o2) {
                        return o1.getXh()-o2.getXh();
                    }
                }
        ).forEach(
                (entity) -> {
                    Map<String, Object> tmpmap = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(entity));
                    tmpmap.put("lxLable", EnumUtils.SEARCHLX.getFormValue(entity.getLx()).getLabel());
                    selectMapList.add(tmpmap);
                }
        );

        //   0#否/1#是
        selectMapList.stream().forEach(selectMap->{
            StringBuilder lxdata = new StringBuilder();
            if (!StringUtil.isEmptyOrLength0(selectMap.get("lxdata"))&&selectMap.get("lxdata").toString().trim().startsWith("(select)")){
                try {
                    List<Map<String,Object>> rows = jdbcTemplate.queryForList(selectMap.get("lxdata").toString().replace("(select)",""));
                    rows.stream().forEach(row->{
                        Set keySet = row.keySet();
                        int i=0;
                        for (Object keyName : keySet) {
                            i++;
                            lxdata.append(row.get(keyName));
                            if (i%2==0){
                                lxdata.append("/");
                            }else {
                                lxdata.append("#");
                            }
                        }

                    });

                }catch (Exception e){
                    e.printStackTrace();
                }

                if (lxdata.toString().endsWith("/")){
                    selectMap.put("lxdata",lxdata.toString().substring(0, lxdata.length() -1));
                }else {
                    selectMap.put("lxdata",lxdata.toString());
                }
            }

            //设置默认值
            if (String.valueOf(selectMap.get("lx")).equals("3")){
                if (!StringUtil.isEmptyOrLength0(selectMap.get("dvalue"))&&!selectMap.get("dvalue").equals("#$#")) {
                    String[] split = String.valueOf(selectMap.get("dvalue")).split("#\\$#");
                    String valueFromItem = EmumUtils.DATETIMEDEFAULT.getValueFromItem(EmumUtils.DATETIMEDEFAULT.valueOf(split[1]), split[0]);
                    selectMap.put("dvalue", valueFromItem);
                }
            }else{
                if(!StringUtil.isEmptyOrLength0(param.get("mDefaultValue_"+selectMap.get("argname")))){
                    selectMap.put("dvalue", param.get("mDefaultValue_"+selectMap.get("argname")));
                }
            }
        });

        model.addAttribute("selectMapList", selectMapList.size()==0?null:StringUtil.escape(JSON.toJSONString(selectMapList)));


        //编辑栏 添加栏
        List<Map<String,Object>> editFieldList = new ArrayList<Map<String,Object>>();
//        List <SysFormListtemplOtherBtnEntity> templOtherBtnEntityList = sysCrfFormListtemplOtherBtnDao.getAllCloneData();
        List <DevtFormListtemplOtherBtnEntity> templOtherBtnEntityList = Lists.newArrayList( sysCrfFormListtemplOtherBtnDao.findAll());
        templOtherBtnEntityList.stream().filter(
                sysCrfFormListtemplTheaderEntity -> {
                    return sysCrfFormListtemplTheaderEntity.getTempleid().equals(param.getOrDefault("tempid", "").toString());
                }
        ).sorted(
                new Comparator<DevtFormListtemplOtherBtnEntity>() {
                    @Override
                    public int compare(DevtFormListtemplOtherBtnEntity o1, DevtFormListtemplOtherBtnEntity o2) {
                        return o1.getXh()-o2.getXh();
                    }
                }
        ).forEach(
                (sysCrfFormTemplateEntity) -> {
                    Map<String, Object> tmpmap = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(sysCrfFormTemplateEntity));
                    tmpmap.put("positionshow","编辑栏");
                    if(sysCrfFormTemplateEntity.getPosition().equalsIgnoreCase("add")){
                        tmpmap.put("positionshow","添加栏");
                    }
                    tmpmap.put("actionshow","弹窗");
                    if(sysCrfFormTemplateEntity.getAction().equalsIgnoreCase("nowin")){
                        tmpmap.put("actionshow","不弹窗");
                    }
                    if(sysCrfFormTemplateEntity.getAction().equalsIgnoreCase("newpage")){
                        tmpmap.put("actionshow","新页面");
                    }
                    tmpmap.put("useflagshow","是");
                    if(sysCrfFormTemplateEntity.getUseflag()==0){
                        tmpmap.put("useflagshow","否");
                    }
                    editFieldList.add(tmpmap);
                }
        );

        model.addAttribute("editFieldList", StringUtil.escape(JSON.toJSONString(editFieldList)));

        return "thymeleaf/devtools30/sysform/v_dldsnformPreview";
    }

    @RequestMapping(value = "/getAllData")
    @ResponseBody
    public Result getAllData(@RequestParam Map<String, Object> param, HttpServletRequest request) {


        //查询控件
        List <DevtFormListtemplArgsEntity> formListtemplArgsEntities =Lists.newArrayList( sysCrfFormListtemplArgsDao.findAll());
        formListtemplArgsEntities.stream().filter(sysCrfFormListtemplTheaderEntity -> {
                    return sysCrfFormListtemplTheaderEntity.getTempleid().equals(param.getOrDefault("tempid", "").toString());
                }
        ).sorted(
                new Comparator<DevtFormListtemplArgsEntity>() {
                    @Override
                    public int compare(DevtFormListtemplArgsEntity o1, DevtFormListtemplArgsEntity o2) {
                        return o1.getXh()-o2.getXh();
                    }
                }
        );


//        System.out.println(JSON.toJSONString(param));
        DevtFormListtemplateEntity sysCrfFormListtemplateEntityTmp = sysCrfFormListTemplateService.getTemplateById(param.get("tempid").toString());

        List<String> keyNameList = new ArrayList<>();

        Set keySet = param.keySet();
        for(Object keyName:keySet) {
            if (keyName.toString().equalsIgnoreCase("page")||keyName.toString().equalsIgnoreCase("limit")||keyName.toString().equalsIgnoreCase("tempid")){
                continue;
            }
            keyNameList.add(keyName.toString());
        }
        String rSql=Util.replaceDefault(sysCrfFormListtemplateEntityTmp.getTemlplesql(),request);

        Map paramMap = new HashMap();

        for (int i = 0; i < formListtemplArgsEntities.size(); i++) {
            DevtFormListtemplArgsEntity sysCrfFormListtemplArgsEntity = formListtemplArgsEntities.get(i);
            Object replacement = param.get(sysCrfFormListtemplArgsEntity.getArgname());
            replacement=StrUtil.isEmptyIfStr(replacement)?"":replacement;
            rSql=rSql.replaceAll("#"+sysCrfFormListtemplArgsEntity.getArgname()+"#",sysCrfFormListtemplArgsEntity.getTjsql().replace("#values#", replacement.toString()));

        }

        int start=StringUtil.isEmptyOrLength0(param.get("page"))?0:Integer.parseInt(param.get("page").toString());
        int limit=StringUtil.isEmptyOrLength0(param.get("limit"))?10:Integer.parseInt(param.get("limit").toString());;


        List<Map<String, Object>> rows = new ArrayList();
        int count = 0;
        if (sysCrfFormListtemplateEntityTmp.getPageflag()!=1) {

            Pagination pagination = new Pagination(rSql.toString(),start,limit,paramMap,namedParameterJdbcTemplate);
            rows=pagination.getResultList();
            count=pagination.getTotalSize();
        }else {
            rows = namedParameterJdbcTemplate.queryForList(rSql.toString(),paramMap);
            count=rows.size();
        }
        List<HashMap> hashMapList=new LinkedList<>();
        rows.stream().forEach(
                stringObjectMap -> {
                    HashMap hashMap=new HashMap();
                    hashMap.putAll(stringObjectMap);
                    List<String> stringList=new LinkedList<>(hashMap.keySet());
                    for (int i = 0; i < stringList.size(); i++) {
                        String key = stringList.get(i);
                        hashMap.put(key.toLowerCase(),stringObjectMap.get(key));
                        hashMap.put(key.toUpperCase(),stringObjectMap.get(key));
                    }
                    hashMapList.add(hashMap);
                }
        );
        return Result.ok(hashMapList,count);
    }

    @RequestMapping(value = "/getJiLianData")
    @ResponseBody
    public Map getJiLianData(String value,@RequestParam Map<String, Object> param){
        Map resultMap = new HashMap();

        JSONObject jsonObject = JSONObject.parseObject(param.get("item").toString());
        System.out.println(JSON.toJSONString(param));

        StringBuilder lxdata=new StringBuilder();

        List<Map<String,Object>> rows = jdbcTemplate.queryForList(StringUtil.isEmptyOrLength0(jsonObject.get("tjsql"))?"":jsonObject.get("tjsql").toString().replace("#value#",value));
        rows.stream().forEach(row->{
            Set keySet = row.keySet();
            int i=0;
            for (Object keyName : keySet) {
                i++;
                lxdata.append(row.get(keyName));
                if (i%2==0){
                    lxdata.append("/");
                }else {
                    lxdata.append("#");
                }
            }

        });

        if (lxdata.toString().endsWith("/")){
            resultMap.put("data",lxdata.toString().substring(0, lxdata.length() -1));
        }else {
            resultMap.put("data",StringUtil.isEmptyOrLength0(lxdata)?null:lxdata);
        }
        resultMap.put("success",true);
        resultMap.put("msg","ok");

        return resultMap;
    }


    @RequestMapping(value = "/getChildGridData")
    @ResponseBody
    public Result getChildGridData(@RequestParam Map<String, Object> param,HttpServletRequest request){

        DevtFormListtemplateEntity sysCrfFormListtemplateEntity = null;
        List<DevtFormListtemplateEntity>  tempfieldlist = sysCrfFormListTemplateService.getFormListtemplateByFormId(param.getOrDefault("tempid", "").toString());
        if (tempfieldlist.size()>0) {
            sysCrfFormListtemplateEntity = tempfieldlist.get(0);
        }
        String sql= Util.replaceDefault(sysCrfFormListtemplateEntity.getTemlplesql(),request ).replace("#value#",param.get("id").toString());

        List rows = jdbcTemplate.queryForList(sql);
        int count = rows.size();

        if (sysCrfFormListtemplateEntity.getPageflag()!=1) {
            rows = Util.startPage(rows, Integer.parseInt(param.get("page").toString()), Integer.parseInt(param.get("limit").toString()));
        }

        return Result.ok(rows,count);
    }
    
    // 主表删除
    @RequestMapping(value = "/delData")
    @ResponseBody
    public Result delData(String tempid,String id){

        List<DevtFormMetadataEntity> crfFormMetadataEntityList= Lists.newArrayList(sysCrfFormMetadataDao.findAll());
        List<DevtModelMetadataTableEntity> tableEntities =commonApiDao.getScrollData(DevtModelMetadataTableEntity.class).getResultlist() ;
        List<Map<String,Object>> mapList = new ArrayList<>();
        crfFormMetadataEntityList.stream().filter(w->
                w.getTempleid().equals(tempid))
                .forEach(m->{
                    Map<String,Object> data=new HashMap<>();
                    data.put("id",m.getId());
                    data.put("name","");
                    data.put("code","");
                    data.put("tableid","");
                    data.put("tabletype","");
                    tableEntities.stream().filter(w->w.getId().equals(m.getTableid())).forEach(tm->{
                        data.put("tableid",m.getTableid());
                        data.put("tabletype",m.getTabletype());
                        data.put("name",tm.getName());
                        data.put("code",tm.getCode());
                    });
                    mapList.add(data);
                });
        
        String  tableName=mapList.get(0).get("code").toString();
        if (StringUtil.isNullOrSpace(tableName)){
            return Result.error("未找到父表，请配置元数据。");
        }
        String sql = "delete from "+tableName+" where id='"+id+"'";

        System.out.println(sql);
        //删除主表数据
        jdbcTemplate.execute(sql);

        return Result.ok("删除成功");
    }
    
    @RequestMapping(value = "/patientDataImport")
    @ResponseBody
    public void patientDataImport(@RequestParam Map<String, Object> param,HttpServletResponse response, String tempid,HttpServletRequest request) throws IOException, SQLException {

        String excelType="xls";
        //查询控件
        List <DevtFormListtemplArgsEntity> formListtemplArgsEntities =Lists.newArrayList( sysCrfFormListtemplArgsDao.findAll());
        formListtemplArgsEntities.stream().filter(sysCrfFormListtemplTheaderEntity -> {
                    return sysCrfFormListtemplTheaderEntity.getTempleid().equals(param.getOrDefault("tempid", "").toString());
                }
        ).sorted(
                new Comparator<DevtFormListtemplArgsEntity>() {
                    @Override
                    public int compare(DevtFormListtemplArgsEntity o1, DevtFormListtemplArgsEntity o2) {
                        return o1.getXh()-o2.getXh();
                    }
                }
        );
        DevtFormListtemplateEntity sysCrfFormListtemplateEntityTmp = sysCrfFormListTemplateService.getTemplateById(tempid);
        String replaceDefault = Util.replaceDefault(sysCrfFormListtemplateEntityTmp.getTemlplesql(), request);
        for (int i = 0; i < formListtemplArgsEntities.size(); i++) {
            DevtFormListtemplArgsEntity sysCrfFormListtemplArgsEntity = formListtemplArgsEntities.get(i);
            Object replacement = param.get(sysCrfFormListtemplArgsEntity.getArgname());
            replacement=StrUtil.isEmptyIfStr(replacement)?"":replacement;
            replaceDefault=replaceDefault.replaceAll("#"+sysCrfFormListtemplArgsEntity.getArgname()+"#",sysCrfFormListtemplArgsEntity.getTjsql().replace("#values#", replacement.toString()));

        }
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(replaceDefault);
        List<DataListCols> tableMapListPatient = sysCrfFormListTemplateService.getDataListColses(sysCrfFormListtemplateEntityTmp);

        List<String> titleList=new ArrayList<String>();
        tableMapListPatient.stream().forEach(p->{
            titleList.add(p.getTitle());
        });

        List excelList = new ArrayList();

        resultList.stream().forEach(result->{
            Set resultKeySet = result.keySet();
            LinkedHashMap tempMap=new LinkedHashMap();
            tableMapListPatient.stream().forEach(p->{
                tempMap.put(p.getTitle(),p.getField());
            });
            Set tempMapKey = tempMap.keySet();
            for (Object tempMapKeyName : tempMapKey) {

                int num=0;
                for (Object resultKeyName : resultKeySet) {
                    if (tempMap.get(tempMapKeyName).toString().equals(resultKeyName.toString())){
                        tempMap.put(tempMapKeyName,StringUtil.isEmptyOrLength0(result.get(resultKeyName))?"":result.get(resultKeyName));
                    }

                    if (!StringUtil.isEmptyOrLength0(result.get(resultKeyName))&&tempMap.get(tempMapKeyName).toString().equalsIgnoreCase(result.get(resultKeyName).toString())){
                        break;
                    }else {
                        if (num==resultKeySet.size()){
                            tempMap.put(tempMapKeyName,"");
                        }
                    }
                    num++;
                }
            }
            excelList.add(tempMap);
        });

        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(excelList);

        ExcelWriter writer = new ExcelWriter();
        if (excelList.size()>60000){
            excelType="xlsx";
            writer=(ExcelWriter)ExcelUtil.getBigWriter();
        }else {
            writer=ExcelUtil.getWriter();
        }

        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+System.currentTimeMillis()/1000+"."+excelType);
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }


    @RequestMapping(value = "/test")
    @ResponseBody
    public Result test(@RequestParam Map param){

        String name = StringUtil.isEmptyOrLength0(param.get("name"))?"":param.get("name").toString();

        String sql = "select * from test_student where name ='"+name+"'";

        List list = jdbcTemplate.queryForList(sql);

        return Result.ok("查询成功了");

    }
}
